﻿using HelperLibrary;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using Quartz.MUI.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Quartz.MUI
{
    public class FmMqttClient
    {
        private static IMqttClient mqttclient = null;
        private static MqttClientOptions options = null;
        /// <summary>
        /// 注册mqtt
        /// </summary>
        public static void ConnectMqttServerAsync(MqttInfo mqttInfo)
        {
            mqttclient = new MqttFactory().CreateMqttClient();
            options = new MqttClientOptionsBuilder()
                   .WithTcpServer(mqttInfo.HostIp, mqttInfo.HostPort)
                   .WithCredentials(mqttInfo.UserName, mqttInfo.Password)
                   .WithClientId($"AVCJOB@SUB|EP#{DateTimeHelper.CreateGUID().ToString().Substring(0, 8)}")
                   .Build();

            mqttclient.ConnectedAsync += Mqttclient_ConnectedAsync;
            mqttclient.DisconnectedAsync += Mqttclient_DisconnectedAsync;
            mqttclient.ConnectAsync(options);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private static Task Mqttclient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
        {
            LogHelper.LogDebug("连接失败");
            mqttclient.ConnectAsync(options);
            return Task.CompletedTask;
        }

        /// <summary>
        /// 链接操作
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private static Task Mqttclient_ConnectedAsync(MqttClientConnectedEventArgs arg)
        {
            LogHelper.LogDebug("连接成功");
            return Task.CompletedTask;
        }

        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="data"></param>
        public static void Publish(string data)
        {
            try
            {
                var message = new MqttApplicationMessage
                {
                    Topic = "/event/status",
                    Payload = Encoding.UTF8.GetBytes(data),
                    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                    Retain = true
                };
                mqttclient.PublishAsync(message);
            }
            catch (Exception ex)
            {
                LogHelper.LogErr(ex);
            }
        }
    }
}
